/*给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
*
* 输入：head = [1,2,3,4,5]
* 输出：[5,4,3,2,1]
* */

package newcoder.LinkedList_2;

 class ListNode1{

    int val;
    ListNode1 next;
    ListNode1(int x){this.val = x;}
    public void add(int x){

        ListNode1 node = new ListNode1(x);
        if (this.next == null) this.next = node;
        else this.next.add(x);
    }

    public void print(){
        System.out.print(this.val);
        if (this.next != null){
            System.out.print("-->");
            this.next.print();
        }
    }

    public ListNode1 reverseList(ListNode1 head){

        if (head == null || head.next ==null){
            return head;
        }
        ListNode1 pre = null;
        ListNode1 curr = head;
        while (curr != null){

            ListNode1 next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }
}


public class Leetcode206 {

    public static void main(String[] args) {

        ListNode1 list = new ListNode1(6);
        list.add(5);
        list.add(4);
        list.add(3);
        list.add(2);
        list.add(1);
        list.print();
        ListNode1 newList = list.reverseList(list);
        System.out.println();
        newList.print();
    }
}
